// pages/class/class.js
import { classificationList, foods } from "../../utils/data.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    classificationList: classificationList,
    typeList: foods.food1,
    topActive: 0,
    navActive: 0,
    scrollDemo: "demo0",
    navHeight: "",
    goodsHeight: "",
    sendArray: ["全部", "今日达", "次日达"],
    sortArray: ["无", "销量", "价格升序", "价格降序"],
    sendIndex: 0,
    sortIndex: 0,
    goodsList: [],
    refreshered: false,
    getMoreIndex: 0,
    touch_down: "",
    touch_start_time:'',
    touch_end_time:'',
    scrollTop: 0,
    oldScrollTop: "",
    showToNextClass: false,
    showMore: false, //是否显示上拉加载更多文案
  },
  //切换顶部分类
  setTopActive(e) {
    let { index, item } = e.currentTarget.dataset;
    this.setData({
      topActive: index
    });
  },
  //切换左侧导航
  setNavActive(e) {
    let { index, item } = e.currentTarget.dataset;
    this.setData({
      navActive: index,
      scrollDemo: "demo" + index
    });
    this.getGoodsList();
  },
  bindSendChange: function(e) {
    this.setData({
      sendIndex: e.detail.value
    });
  },
  bindSortChange(e) {
    this.setData({
      sortIndex: e.detail.value
    });
  },
  //刷新商品
  refreshGoods(e) {
    if (this.data.refreshered) return;
    this.setData({
      refreshered: true
    });
    setTimeout(() => {
      this.setData({
        refreshered: false
      });
    }, 1000);
  },
  //上拉触底加载更多
  getMore() {    
    if (this.data.getMoreIndex >= 2) return;
    let list = [
      {
        did: "1",
        cover:
          "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg",
        title: "新增的1",
        price: 15
      },
      {
        did: "1",
        cover:
          "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg",
        title: "新增的1",
        price: 15
      }
    ];
    this.setData({
      goodsList: this.data.goodsList.concat(list),
      getMoreIndex: this.data.getMoreIndex + 1
    });
    this.scrollTop = 0;
  },
  //获取商品列表
  getGoodsList() {
    this.setData({
      getMoreIndex: 0,
      showToNextClass: false,
    });
    wx.showLoading()
    setTimeout(() => {
      let Ram = parseInt(this.data.navActive) + 5;
      let arr = [];
      let obj = {
        did: "1",
        cover:
          "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1906469856,4113625838&fm=26&gp=0.jpg",
        title: "低价处理了",
        price: 15
      };
      for (let i = 0; i < Ram; i++) {
        arr.push(obj);
      }
      wx.hideLoading()
      this.setData({
        goodsList: arr,
        scrollTop: 0,
      });
    }, 300);
  },

  //触摸开始
  start_fn(e) {
    let touch_down = e.touches[0].clientY;
    this.setData({
      touch_down: touch_down,
      touch_start_time:new Date().getTime()
    });
  },
  //触摸过程中
  move_fn(e) {
    var currentY = e.touches[0].pageY;
    if (this.data.touch_down - currentY > 100) {
      this.setData({
        showToNextClass: true
      });
    } else {
      this.setData({
        showToNextClass: false
      });
    }
  },
  //触摸结束
  end_fn(e) {
    let end_time = new Date().getTime()
    if(end_time - this.data.touch_start_time <300) return 
    let current_y = e.changedTouches[0].clientY;
    let { touch_down } = this.data;
    if (current_y < touch_down && touch_down - current_y > 100) {
      if (this.data.goodsList.length < 4 || this.data.getMoreIndex >= 2) {
        this.setData({
          navActive: this.data.navActive + 1,
          scrollDemo: "demo" + (this.data.navActive + 1)
        });
        this.getGoodsList();
      }
    }
  },
  //跳转搜索页面
  toSearch(){
    wx.navigateTo({
      url: '/pages/search',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let windowHeight = wx.getStorageSync("windowHeight"); 
    console.log(windowHeight)   
    let height = windowHeight -wx.getStorageSync("statusBarHeight")    
    this.setData({
      navHeight: height -150 +'px',
      goodsHeight: height-200 +"px"
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    console.log("onReady");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    console.log("show");
    this.getGoodsList();    
    wx.getLocation({
      type: 'wgs84',
      success (res) {
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy
        console.log(res)
      },
      fail(err){
        wx.getSetting({
          success (res) {
            console.log(res.authSetting)
            // res.authSetting = {
            //   "scope.userInfo": true,
            //   "scope.userLocation": true
            // }
            const flag = res.authSetting['scope.userLocation']
            if(!flag){
              wx.showModal({
                content: '检测到您没打开定位权限，是否去设置打开？',
                confirmText: "确认",
                cancelText: "取消",
                success: function (res) {
                  console.log(res);
                  //点击“确认”时打开设置页面
                  if (res.confirm) {
                    console.log('用户点击确认')
                    wx.openSetting({
                      success: (res) => { }
                    })
                  } else {
                    console.log('用户点击取消')
                  }
                }
              });
            }
          }
        })
      }
     })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    console.log("上拉");
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
